#!/bin/bash

# 设置颜色
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # 无颜色

# 基础URL
BASE_URL="http://localhost:3000/api/v1"
TEST_USERNAME="testuser_$(date +%s)"
TEST_EMAIL="${TEST_USERNAME}@example.com"
TEST_PASSWORD="Test@1234"
JWT_TOKEN=""

# 输出分隔线
print_separator() {
  echo -e "\n${YELLOW}========================================${NC}\n"
}

# 测试函数
test_api() {
  local description=$1
  local method=$2
  local endpoint=$3
  local data=$4
  local auth_header=$5

  echo -e "${YELLOW}测试: ${description}${NC}"
  echo "端点: ${method} ${endpoint}"
  if [ -n "$data" ]; then
    echo "请求体: $data"
  fi

  if [ -n "$auth_header" ]; then
    response=$(curl -s -X ${method} \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer ${auth_header}" \
      ${data:+-d "${data}"} \
      "${BASE_URL}${endpoint}")
  else
    response=$(curl -s -X ${method} \
      -H "Content-Type: application/json" \
      ${data:+-d "${data}"} \
      "${BASE_URL}${endpoint}")
  fi

  echo "响应: $response"
  echo
  
  # 返回响应以便进一步处理
  echo "$response"
}

# 测试健康检查
print_separator
echo "测试健康检查..."
curl -s http://localhost:3000/api/v1/health
echo
print_separator

# 测试用户注册
echo "测试用户注册..."
REGISTER_DATA="{\"username\":\"${TEST_USERNAME}\",\"password\":\"${TEST_PASSWORD}\",\"email\":\"${TEST_EMAIL}\",\"name\":\"测试用户\",\"role\":\"student\"}"
REGISTER_RESPONSE=$(test_api "用户注册" "POST" "/auth/register" "$REGISTER_DATA")

# 测试用户登录
print_separator
echo "测试用户登录..."
LOGIN_DATA="{\"email\":\"${TEST_EMAIL}\",\"password\":\"${TEST_PASSWORD}\"}"
LOGIN_RESPONSE=$(test_api "用户登录" "POST" "/auth/login" "$LOGIN_DATA")

# 从登录响应中提取token
JWT_TOKEN=$(echo $LOGIN_RESPONSE | grep -o '"token":"[^"]*' | cut -d'"' -f4)
if [ -n "$JWT_TOKEN" ]; then
  echo -e "${GREEN}成功获取JWT令牌: ${JWT_TOKEN:0:20}...${NC}"
else
  echo -e "${RED}无法获取JWT令牌${NC}"
fi

# 测试获取当前用户信息
print_separator
echo "测试获取当前用户信息..."
test_api "获取当前用户信息" "GET" "/users/me" "" "$JWT_TOKEN"

# 测试获取所有课程
print_separator
echo "测试获取所有课程..."
COURSES_RESPONSE=$(test_api "获取所有课程" "GET" "/courses" "" "$JWT_TOKEN")

# 从课程列表中提取第一个课程ID
COURSE_ID=$(echo $COURSES_RESPONSE | grep -o '"id":[0-9]*' | head -1 | cut -d':' -f2)
if [ -n "$COURSE_ID" ]; then
  echo -e "${GREEN}找到课程ID: $COURSE_ID${NC}"
else
  # 如果没有找到课程ID，使用默认值1
  COURSE_ID=1
  echo -e "${YELLOW}未找到课程ID，使用默认值: $COURSE_ID${NC}"
fi

# 测试选课
print_separator
echo "测试选课..."
ENROLL_DATA="{\"courseId\":$COURSE_ID}"
test_api "选课" "POST" "/enrollments" "$ENROLL_DATA" "$JWT_TOKEN"

# 测试获取我的选课
print_separator
echo "测试获取我的选课..."
test_api "获取我的选课" "GET" "/enrollments/me" "" "$JWT_TOKEN"

# 测试获取所有用户（需要管理员权限）
print_separator
echo "测试获取所有用户（需要管理员权限）..."
test_api "获取所有用户" "GET" "/users" "" "$JWT_TOKEN"

# 测试登出
print_separator
echo "测试用户登出..."
test_api "用户登出" "POST" "/auth/logout" "" "$JWT_TOKEN"

print_separator
echo -e "${GREEN}测试完成！${NC}"
